<?php
/**
 *	[push(push.{modulename})] (C)2012-2099 Powered by abans@qq.com.
 *	Version: 1.0
 *	Date: 2012-11-30 13:35
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}
loadcache('plugin');
if(!defined('Adz_class')){include('Adz.class.php');}
include('push.fun.php');
class plugin_push {}
class plugin_push_forum extends plugin_push {
	function plugin_push_forum(){
		global $_G;
		$this->_G = $_G;
		$this->siteurl = $_G['siteurl'];
		$this->friend = $_G['member_'.$_G['uid'].'_field_home']['feedfriend'];//好友列表
		if(!empty($this->friend)) $this->friend_sql = 'and m.uid in ('.$this->friend.')';
		$this->def = push_set_data($_G['uid']);//用户的订阅配置
		$this->group = unserialize($_G['cache']['plugin']['push']['group']);//用户组配置
		if($this->group[0]>0){
			$this->group_where = 'groupid in ('.implode(',',$this->group).')';
		}
		$this->bk = unserialize($_G['cache']['plugin']['push']['bankuai']);//板块配置
		$this->thread = $_G['forum_thread'];//帖子数据
		if(in_array($_G['groupid'],$this->group) || $this->group[0]==''){
			if($_G['groupid']!=7)
			$this->power = true;
		}else{$this->power = false;}
		//如果是帖子页面,检测板块权限
		if($_G['forum']['fid']){
			if(in_array($_G['forum']['fid'],$this->bk) || $this->bk[0]==''){
				$this->power_bk = true;
			}else{
				$this->power_bk = false;
			}
		}
		$this->conf = $_G['cache']['plugin']['push'];
		$this->mail_sign = $_G['cache']['plugin']['push']['mail_sign'];
		$this->sendlimit = $_G['cache']['plugin']['push']['num'];
		if($this->sendlimit > 0){$this->sendlimit = 'LIMIT '.$this->sendlimit;}else{$this->sendlimit = 'LIMIT 3';}
	}
	function rate_html($type='mail',$val){
		$enum = array(
			0=>lang('plugin/push','bind_rate0'),
			1=>lang('plugin/push','bind_rate1'),
			2=>lang('plugin/push','bind_rate2'),
			3=>lang('plugin/push','bind_rate3')
		);
		$html = "<select name=\"$type\" onchange=\"Adz_push_bind(".$this->_G['tid'].")\">\n";
		$arr = explode("\n",$pluginid['bind_rate']);
		foreach ($enum as $key => $option) {
			$html .= "<option value=\"".dhtmlspecialchars($key)."\" ".($key==$val ? 'selected="selected"' : '').">$option</option>\n";
		}
		return $html .= "</select>\n";
	}
	/**浏览帖子标题挂载点 */
	function viewthread_title_extra() {
		if(!$this->power){return;}
		if(!$this->power_bk){return;}
		if($this->thread['authorid']!=$this->_G['uid'] && $this->_G['groupid']!=1){return;}
		$data = Adz::fetch_con('plugin_push_bind',array('rid'=>$this->_G['tid']));
		if($data['mail']==1){$mail_chk = 'checked="checked"';}
		$html = Adz::acan_ui('push').'<script>
function Adz_push_bind(rid){
	var mail = jQuery(".Adz_push_bind select[name=\"mail\"]");
	var data = {"save":{"rid":rid,"mail":mail.val()}};
	jQuery.ajax({
		async : false,
		type:"POST",url:"plugin.php?id=push:post",data:data,
		beforeSend: function(){Acan.alert(Alang.ajax_start);},
		ajaxSend: function(){Acan.alert(Alang.ajax_send);},
		success: function(data){
			if(typeof(data)=="object"){
				Acan.alert(data.msg,1500);
			}else{
				Acan.alert("error",1000);
			}
		}
	});
}
</script>';
		$html .= '<span class="Adz_push_bind">'.lang('plugin/push','push_title').':';
		$html .= lang('plugin/push','mail').' '.$this->rate_html('mail',$data['mail']);
		$html .= '</span>';
		return $html;
	}
	/**发帖回帖成功挂载点 */
	function post_sync_to_push_aftersubmit_message($param) {
		if(!$this->power_bk){return;}
		if($this->_check_is_forum_post($param)==1){
			$this->push($param['param'][2],1);
		}elseif($this->_check_is_forum_post($param)==2){
			$this->push($param['param'][2],2);
		}
	}
	function push($arr,$type=1){
		$username = $this->_G['username'];
		if(!empty($this->group_where)){
			$group_where = 'and m.'.$this->group_where;
		}else{
			$group_where = '';
		}
		$pdata = Adz::fetch_con('forum_post',array('pid'=>$arr['pid']),'authorid,dateline,message,tid,subject');
		$tdata = $this->thread;
		if($type==1){
			//主题@提醒，如果改用户没有权限无法提醒
			if(!$this->power){return;}
			$tdata = $pdata;
			//默认订阅频率
			if($this->conf['bind_rate']>0){
				Adz::mysql_save('plugin_push_bind',array('mail'=>$this->conf['bind_rate']),array('rid'=>$pdata['tid']));
			}
		}
		if($type==2){
			preg_match('/\[quote\](.*?)pid\=([0-9]+)\&ptid\=([0-9]+)/',$pdata['message'],$match);
			//回复回帖mail提醒
			if($match[2]>0 && $this->def['mail']['f_rp2']==1){
				$ppdata = DB::fetch_first('SELECT a.authorid,a.dateline,a.message FROM '.DB::table('forum_post').' a LEFT JOIN '.DB::table('common_member').' m ON m.uid=a.authorid WHERE m.emailstatus=1 and a.pid='.$match[2].' '.$group_where.' LIMIT 1');
				if($ppdata && $ppdata['authorid']!=$pdata['authorid']){
					$rid = $ppdata['authorid'];
					DB::insert('plugin_push_log',array('uid'=>$rid,'rid'=>$arr['pid'],'date'=>date("Y-m-d H:i:s"),'type'=>1,'title'=>$this->mail_title_rp($username,'',2)));
				}
			}
			//回复主题mail提醒
			if($pdata['authorid']!=$tdata['authorid'] && $this->def['mail']['f_rp']==1){
				if(empty($rid) || $rid!=$tdata['authorid']){
					$rp2_uid = $tdata['authorid'];
					//如果是主题则查询绑定的状态
					$data = Adz::fetch_con('plugin_push_bind',array('rid'=>$pdata['tid']));
					if($data && $data['mail']>0){
						if($data['mail']==2){//每日一次
							$mdate = Adz::get_time('date').' 00:00:00';
						}else if($data['mail']==3){//每周一次
							$mdate = date('Y-m-d',Adz::time_ex(Adz::get_time('time'),-6)).' 00:00:00';
						}
						//查询发送记录
						if($mdate) $olds = DB::fetch_first('SELECT a.id FROM '.DB::table('plugin_push_log').' a LEFT JOIN '.DB::table('forum_post').' p ON a.rid=p.pid WHERE a.uid='.$tdata['authorid'].' and p.tid='.$pdata['tid'].' and a.date>\''.$mdate.'\'');
						if($data['mail'] > 1 && empty($olds['id']) || $data['mail'] == 1){
							$udata = DB::fetch_first('SELECT m.uid FROM '.DB::table('common_member').' m WHERE m.emailstatus=1 and m.uid='.$tdata['authorid'].' '.$group_where.' LIMIT 1');
							if($udata) DB::insert('plugin_push_log',array('uid'=>$tdata['authorid'],'rid'=>$arr['pid'],'date'=>date("Y-m-d H:i:s"),'type'=>1,'title'=>$this->mail_title_rp($username,$tdata['subject'])));
						}
					}
				}
			}
		}
		//好友@提到 mail提醒
		if(!empty($this->friend)){
			preg_match_all("/@([^:&@\$\?\/\[\r\n]*?)([:&@\/\?\$\s\[])/i", $pdata['message'].' ', $match2);
			file_put_contents(DISCUZ_ROOT.'source/plugin/push/log.txt',json_encode($match2));
			$atlist = array_unique($match2[1]);
			if(count($atlist)>0 && $this->def['mail']['f_rp3']==1){
				$udata = Adz::fetch_all('SELECT * FROM '.DB::table('common_member').' m WHERE m.emailstatus=1 '.$this->friend_sql.' and m.username in (\''.implode("','",$atlist).'\') '.$group_where);
				if($udata)
				foreach ($udata as $k => $v) {
					if($v['uid']==$this->_G['uid'] || $v['uid']==$rid || $v['uid']==$rp2_uid) continue;
					DB::insert('plugin_push_log',array('uid'=>$v['uid'],'rid'=>$arr['pid'],'date'=>date("Y-m-d H:i:s"),'type'=>1,'title'=>$this->mail_title_rp($username,$tdata['subject'],3)));
				}
			}
		}
		$this->send();
	}
	//帖子回复
	function mail_title_rp($username,$subject='',$type=1){
		if($type==1)
			return str_replace(array('{username}','{subject}'),array($username,$subject),$this->conf['mail_title_rp']);
		else
			return str_replace(array('{username}','{subject}'),array($username,$subject),$this->conf['mail_title_rp'.$type]);
	}
	function mail_sign($tid){
		$addurl = '&afrom=push_mail';
		$turl="http://".Adz::subdomain('forum').$this->_G['siteroot'].'forum.php?mod=redirect&goto=findpost&pid='.$tid.$addurl;
		$tuidingurl = $this->_G['siteurl'].'home.php?mod=spacecp&ac=plugin&id=push:set'.$addurl;
		$arr1 = array('{siteurl}','{sitename}','{adminemail}','{tuidingurl}','{turl}');
		$arr2 = array($this->_G['siteurl'],$this->_G['setting']['sitename'],$this->_G['setting']['adminemail'],$tuidingurl,$turl);
		return str_replace($arr1,$arr2,$this->mail_sign);
	}
	function send(){
		$data = Adz::fetch_all('SELECT a.*,m.email,p.message,p.tid,p.first,p.authorid FROM '.DB::table('plugin_push_log').' a LEFT JOIN '.DB::table('common_member').' m ON m.uid=a.uid LEFT JOIN '.DB::table('forum_post').' p ON a.rid=p.pid WHERE a.status=0 and a.type=1 and m.emailstatus=1 '.$this->sendlimit);
		if(is_array($data))
		foreach ($data as $k => $v) {
			if(Adz::Amail($v['email'],$v['title'],str_replace('{note}',str_replace(array('src="static/'),array('src="'.$this->siteurl.'static/'),discuzcode($v['message'],0,0)),$this->conf['mail_note']).$this->mail_sign($v['rid']))){
				DB::update('plugin_push_log', array('status'=>1), array('id'=>$v['id']));
			}
		}
	}
	/**检测发帖回帖类型 */
	function _check_is_forum_post($param) {
		global $_G;
		if(!$_G['uid'] || 'POST' != $this->_get_request_method() || substr($param['param'][0], -8) != '_succeed'){
			return 0;
		}else if(isset($param['param'][2]['tid']) && ($param['param'][2]['tid'] > 0)){
			if(submitcheck('topicsubmit') && $_G['gp_action'] == 'newthread'){
				//&& $_G['cache']['plugin']['alias']['ping_new']
				return 1;
			}else if(submitcheck('replysubmit') && $_G['gp_action'] == 'reply'){
				//&& $_G['cache']['plugin']['alias']['ping_reply']
				return 2;
			}else if(submitcheck('editsubmit') && $_G['gp_action'] == 'edit'){
				//&& $_G['cache']['plugin']['alias']['ping_edit']
				return 0;
			}else{
				return 0;
			}
		}else{
			return 0;
		}
	}
	function _get_request_method() {
		static $_requestMethod = null;
		if( null == $_requestMethod ){
			$_requestMethod = isset($_SERVER['REQUEST_METHOD']) ? strtoupper($_SERVER['REQUEST_METHOD']) : '';
		}
		return $_requestMethod;
	}
}

?>